/* */
<template>
  <div class="raw_field_editor" @blur="onBlur" :style="customInputVar">
    <el-row>
      <el-col
        :span="field.hasHistoryData() || field.getUniqueCheck() ? 22 : 24"
      >
        <!--主体内容-->

        <template>
          <div v-if="['ImgBin', 'ImgUrl'].includes(field.info.srvCol.col_type)">
            <!-- 二进制文件 -->
            <el-image
              v-if="field.info.srvCol.col_type === 'ImgBin'"
              style="width: 50px; height: 50px"
              :src="blobToBase64(field.model)"
              fit="cover"
            >
            </el-image>
            <!-- 在线url -->
            <el-image
              v-else-if="field.info.srvCol.col_type === 'ImgUrl'"
              style="width: 50px; height: 50px"
              :src="setImgUrl(field.model)"
              fit="cover"
            >
            </el-image>
          </div>
          <div v-else-if="ifUseRawFieldEditor()">
            <car-no-keyboard
              :field="field"
              v-if="field.info.editor === 'carNoKeyboard'"
              v-model="field.model"
              :readonly="getDisabled"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
              @onBlur="onBlur"
            >
            </car-no-keyboard>
            <bx-input-number
              v-else-if="field.info.editor === 'input-number'"
              controls-position="right"
              v-model="field.model"
              :disabled="getDisabled"
              :min="field.info.getMin()"
              :max="field.info.getMax()"
              label="描述文字"
              :fieldMoreConfig="field.info"
              @change="$emit('field-value-changed', field.info.name, field)"
              @blur="onBlur"
            >
            </bx-input-number>
            <el-input
              v-else-if="field.info.editor === 'textarea'"
              type="textarea"
              :rows="5"
              :placeholder="field.info.placeholder"
              :disabled="getDisabled"
              show-word-limit
              :minlength="field.info.getMinLength()"
              :maxlength="field.info.getMaxLength()"
              @input="checkLength"
              v-model="field.model"
              @change="$emit('field-value-changed', field.info.name, field)"
              @blur="onBlur"
            >
              <!-- style="height:80px;" -->
            </el-input>
            <el-switch
              v-else-if="field.info.editor === 'switch'"
              v-model="field.model"
              active-color="#13ce66"
              inactive-color="#777777"
            >
            </el-switch>

            <el-select
              v-else-if="field.info.editor === 'select'"
              v-model="field.model"
              :placeholder="field.info.placeholder"
              clearable
              :disabled="getDisabled"
              @change="selectChange"
              @blur="onBlur"
            >
              <el-option
                v-for="item in field.optionsFunc()"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <div
                  v-if="
                    item.label &&
                    (item.label.startsWith('ri-') ||
                      item.label.startsWith('ri:'))
                  "
                  class="flex items-center"
                  style="width: 100%; height: 100%; font-size: 24px"
                >
                  <Icon :icon="item.label" />
                </div>
                <span v-else>{{ item.label }}</span>
              </el-option>
            </el-select>

            <userlist
              v-else-if="field.info.editor === 'userlist'"
              :field="field"
              ref="editor"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
            >
            </userlist>

            <ueditorPlus
              :field="field"
              ref="snote"
              v-else-if="field.info.editor == 'snote'"
              @field-changed="
                $emit('field-value-changed', field.info.name, field)
              "
            >
            </ueditorPlus>
            <wang-editor
              ref="editor"
              :disabled="getDisabled"
              :field="field"
              v-model="field.model"
              @change="$emit('field-value-changed', field.info.name, field)"
              v-else-if="field.info.editor === 'ueditor'"
            >
            </wang-editor>
            <!-- <wang-editor
              ref="editor"
              :disabled="getDisabled"
              :field="field"
              v-model="field.model"
              @change="$emit('field-value-changed', field.info.name, field)"
              v-else-if="
                field.info.editor === 'ueditor' &&
                field.info.moreConfig &&
                field.info.moreConfig.mode === 'modern'
              "
            >
            </wang-editor> -->
            <TinymceEditor
              :disabled="getDisabled"
              v-else-if="field.info.editor === 'ueditor'"
              :field="field"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
              ref="editor"
            ></TinymceEditor>
            <!-- <ueditor
              v-else-if="field.info.editor === 'ueditor'"
              :field="field"
              @field-changed="
                $emit('field-value-changed', field.info.name, field)
              "
              ref="editor"
            >
            </ueditor> -->

            <el-date-picker
              v-else-if="
                field.info.editor === 'date-picker' && field.model !== '******'
              "
              v-model="field.model"
              :type="field.info.subtype"
              clearable
              :format="
                field.info.subtype == 'year'
                  ? 'yyyy年'
                  : field.info.subtype == 'month'
                  ? 'yyyy 年 MM 月'
                  : field.info.subtype == 'week'
                  ? 'yyyy 第 WW 周'
                  : 'yyyy 年 MM 月 dd 日'
              "
              :disabled="getDisabled"
              :placeholder="field.info.placeholder"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              @change="$emit('field-value-changed', field.info.name, field)"
            >
            </el-date-picker>

            <el-date-picker
              v-else-if="
                field.info.editor === 'date-time-picker' &&
                field.model !== '******'
              "
              v-model="field.model"
              type="datetime"
              clearable
              :format="field.info.format ? field.info.format : null"
              :value-format="field.info.format ? field.info.format : null"
              :disabled="getDisabled"
              :placeholder="
                field.model !== '******' ? field.info.placeholder : field.model
              "
              @change="$emit('field-value-changed', field.info.name, field)"
              @blur="onBlur"
            >
            </el-date-picker>

            <el-time-picker
              v-else-if="
                field.info.editor === 'time-picker' && field.model !== '******'
              "
              :picker-options="{ format: 'HH:mm' }"
              value-format="HH:mm"
              v-model="field.model"
              clearable
              :disabled="getDisabled"
              :placeholder="field.info.placeholder"
              @change="$emit('field-value-changed', field.info.name, field)"
              @blur="onBlur"
            >
            </el-time-picker>

            <el-select
              v-else-if="field.info.editor === 'multiselect'"
              v-model="field.model"
              multiple
              collapse-tags
              clearable
              filterable
              :disabled="getDisabled"
              :placeholder="field.info.placeholder"
              @change="$emit('field-value-changed', field.info.name, field)"
            >
              <el-option
                v-for="item in field.optionsFunc()"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>

            <!-- range -->
            <el-date-picker
              v-else-if="field.info.editor === 'date-range'"
              v-model="field.model"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
              :disabled="getDisabled"
              :placeholder="field.info.placeholder"
              @change="$emit('field-value-changed', field.info.name, field)"
              @blur="onBlur"
            >
            </el-date-picker>
            <!-- DateRange -->
            <el-date-picker
              v-else-if="
                field.info.editor === 'DateRange' &&
                field.info._DateRangeEndColName
              "
              v-show="field.info._DateRangeEndColName"
              v-model="field['_DateRangeModel']"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
              :picker-options="pickerOptions"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              :disabled="getDisabled"
              :placeholder="field.info.placeholder"
              @blur="$emit('field-value-changed', field.info.name, field)"
            >
            </el-date-picker>
            <!-- DateRange 只读-->
            <el-input
              v-else-if="
                field.info.editor === 'DateRange' &&
                !field.info._DateRangeEndColName
              "
              readonly
              :type="field.info.editor === 'Password' ? 'password' : 'text'"
              v-show="!field.info._DateRangeEndColName"
              :value="field.getDispVal4Read()"
            >
            </el-input>
            <el-time-picker
              v-else-if="field.info.editor === 'time-range'"
              is-range
              v-model="field.model"
              :picker-options="{ format: 'HH:mm' }"
              value-format="HH:mm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
              :disabled="getDisabled"
              :placeholder="field.info.placeholder"
              @change="$emit('field-value-changed', field.info.name, field)"
            >
            </el-time-picker>

            <el-date-picker
              v-else-if="field.info.editor === 'date-time-range'"
              v-model="field.model"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
              :disabled="getDisabled"
              :placeholder="field.info.placeholder"
              @change="changeDependField(field)"
            >
            </el-date-picker>

            <input-range
              v-else-if="field.info.editor === 'input-range'"
              :field="field"
              ref="editor"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
            >
            </input-range>

            <upload-file
              v-else-if="field.info.editor === 'upload-file'"
              :field="field"
              @more-info="getMoreInfo($event)"
              :limit="uploadLimit"
              ref="editor"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
            >
            </upload-file>

            <upload-image
              v-else-if="field.info.editor === 'upload-image'"
              :field="field"
              :limit="uploadLimit"
              ref="editor"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
            >
            </upload-image>
            <!-- 穿梭框 -->
            <transfer-vue
              v-else-if="field.info.isTransfer"
              v-model="field.finderSelected"
              :disabled="getDisabled"
              :field="field"
              :defaultCondition="defaultCondition"
              :defaultValues="defaultValues"
              :childForeignKey="childForeignkey"
              :mainFormDatas="mainformDatas"
              :form-model="formModel"
              :$srv-app="
                field.info.srvCol.option_list_v2 &&
                field.info.srvCol.option_list_v2.srv_app
              "
              ref="editor"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
              @blur="onBlur"
            >
            </transfer-vue>
            <finder
              v-else-if="field.info.editor === 'finder'"
              :disabled="getDisabled"
              :field="field"
              v-model="field.finderSelected"
              :defaultCondition="defaultCondition"
              :defaultValues="defaultValues"
              :childForeignkey="childForeignkey"
              :mainformDatas="mainformDatas"
              :form-model="formModel"
              :$srv-app="
                field.info.srvCol.option_list_v2 &&
                field.info.srvCol.option_list_v2.srv_app
              "
              ref="editor"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
              @blur="onBlur"
            >
            </finder>

            <multiFinder
              v-else-if="field.info.editor === 'multifinder'"
              :field="field"
              :$srv-app="
                field.info.srvCol.option_list_v2 &&
                field.info.srvCol.option_list_v2.srv_app
              "
              ref="editor"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
              @blur="onBlur"
            >
            </multiFinder>
            <tree-finder
              :disabled="getDisabled"
              v-else-if="field.info.editor === 'tree-finder'"
              ref="editor"
              :field="field"
              :$srv-app="field.info.srvCol.option_list_v2.srv_app"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
            >
            </tree-finder>

            <qr-code
              v-else-if="field.info.editor === 'qrcode'"
              ref="editor"
              :field="field"
            >
            </qr-code>

            <code-editor
              v-else-if="field.info.editor === 'code-editor'"
              ref="editor"
              :field="field"
              :lang="field.info.lang"
            >
            </code-editor>
            <vue-json-editor
              v-else-if="field.info.editor === 'json-editor'"
              :value="getJsonModel"
              :lang="'zh'"
              :mode="getDisabled ? 'view' : 'code'"
              :modes="getDisabled ? ['view'] : ['code', 'tree', 'form', 'view']"
              :show-btns="false"
              :expandedOnStart="true"
              style="margin-bottom: 10px"
              @json-change="jsonChange"
              @has-error="jsonError"
            ></vue-json-editor>
            <json-table-editor
              v-else-if="field.info.editor === 'json-table-editor'"
              :field="field"
              v-model="field.model"
              @change="$emit('field-value-changed', field.info.name, field)"
            ></json-table-editor>
            <!-- <json-editor
              v-else-if="field.info.editor === 'json-editor'"
              ref="editor"
              :stringified="true"
              :statusBar="false"
              :navigationBar="false"
              :mainMenuBar="false"
              :readOnly="getDisabled"
              :value="field.model || ''"
              :mode="jsonEditorMode"
              :onChange="jsonChange"
              @blur="onBlur"
            ></json-editor> -->
            <radio
              v-else-if="field.info.editor === 'radio'"
              ref="editor"
              :field="field"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
            >
            </radio>

            <checkbox
              v-else-if="field.info.editor === 'checkbox'"
              ref="editor"
              :field="field"
              @field-value-changed="
                $emit('field-value-changed', field.info.name, field)
              "
            >
            </checkbox>
            <el-input
              v-else-if="field.info.editor === 'Password'"
              v-model="field.model"
              :placeholder="field.info.placeholder"
              :disabled="getDisabled"
              clearable
              type="password"
              show-word-limit
              :maxlength="field.info.getMaxLength()"
              @input="checkLength"
              @change="$emit('field-value-changed', field.info.name, field)"
              @blur="onBlur"
            >
              <template
                slot="append"
                v-if="field.info.moreConfig && field.info.moreConfig.appendText"
                >{{ field.info.moreConfig.appendText }}</template
              >
              <template
                slot="prepend"
                v-if="
                  field.info.moreConfig && field.info.moreConfig.prependText
                "
                >{{ field.info.moreConfig.prependText }}</template
              >
            </el-input>

            <div v-else-if="field.info.editor == 'extend'">
              <dynamicSubTemp
                ref="dynSub"
                :config="field.info.moreConfig"
                :field="field"
                :form="field.form"
              ></dynamicSubTemp>
            </div>
            <!-- default -->
            <div v-else-if="field.info.editor == 'verifySmsCode'">
              <verifyMobile
                ref="verifyMobile"
                @change="$emit('field-value-changed', field.info.name, field)"
                :field="field"
              >
              </verifyMobile>
            </div>
            <div
              v-else-if="
                field.info.editor == null &&
                field.info.type == 'String' &&
                field.autocompleteInput &&
                field.isAutocomplete()
              "
            >
              <!-- 字符串类型的外键冗余字段 获得建议输入选项特性 -->
              <autocompleteInput
                ref="autocompleteInput"
                :disabled="getDisabled"
                @change="autocompleteSelected"
                @field-value-changed="$emit('field-value-changed', $event)"
                :field="field"
              ></autocompleteInput>
            </div>
            <div
              v-else-if="
                field.info.editor == null &&
                field.info.type == 'String' &&
                field.info.subType == 'autocomplete' &&
                (field.autocompleteInput || field.stringAutocompleteInput)
              "
            >
              <!-- 字符串类型的外键冗余字段 获得建议输入选项特性 -->
              <autocompleteInput
                ref="autocompleteInput"
                @change="autocompleteSelected"
                :field="field"
              ></autocompleteInput>
            </div>
            <div
              v-else-if="field.info.editor == 'color-picker'"
              class="color-picker"
              :class="{
                focus: inputStatus === 'focus',
              }"
            >
              <input
                type="color"
                class="color-picker-input"
                id="head"
                name="head"
                v-model="field.model"
                @change="$emit('field-value-changed', field.info.name, field)"
              />

              <input
                type="text"
                class="color-picker-text"
                v-model="field.model"
                @change="$emit('field-value-changed', field.info.name, field)"
                @blur="onBlur"
                @focus="inputStatus = 'focus'"
              />
            </div>
            <el-input
              :prefix-icon="elIconPrefix"
              v-else
              v-model="field.model"
              :placeholder="field.info.placeholder"
              :disabled="getDisabled"
              clearable
              show-word-limit
              :maxlength="field.info.getMaxLength()"
              @input="checkLength"
              @change="$emit('field-value-changed', field.info.name, field)"
              @blur="onBlur"
            >
              <template
                slot="append"
                v-if="field.info.moreConfig && field.info.moreConfig.appendText"
              >
                {{ field.info.moreConfig.appendText }}
              </template>
              <template
                slot="prepend"
                v-if="
                  field.info.moreConfig && field.info.moreConfig.prependText
                "
                >{{ field.info.moreConfig.prependText }}
              </template>
            </el-input>
          </div>
          <div
            v-else-if="field.info.editor == 'textarea'"
            v-show="field.info.bodyVisible"
            style="
              border-radius: 4px;
              border: 1px solid #dcdfe6;
              overflow: auto;
              word-break: break-all;
              padding: 0 15px;
            "
          >
            {{ field.getDispVal() }}
          </div>
          <div v-else-if="field.info.editor == 'extend'">
            <dynamicSubTemp
              ref="dynSub"
              :config="field.info.moreConfig"
              :field="field"
              :form="field.form"
            ></dynamicSubTemp>
          </div>

          <template v-else>
            <!--只读编辑器-->
            <bx-input-number
              v-if="
                field.info.editor === 'input-number' &&
                ['progress', 'rate'].includes(field.info.subType)
              "
              controls-position="right"
              v-model="field.model"
              :disabled="true"
              :min="field.info.getMin()"
              :max="field.info.getMax()"
              label="描述文字"
              :fieldMoreConfig="field.info"
              @change="$emit('field-value-changed', field.info.name, field)"
              @blur="onBlur"
            >
            </bx-input-number>
            <a
              v-else-if="field.info.linkUrlFunc"
              v-show="field.getSrvVal()"
              style="white-space: normal; color: dodgerblue; cursor: pointer"
              @click="onLinkClicked()"
            >
              {{ field.getDispVal4Read() }}
            </a>

            <el-input
              v-else
              readonly
              :type="field.info.editor === 'Password' ? 'password' : 'text'"
              v-show="field.info.bodyVisible"
              :disabled="getDisabled"
              :value="field.getDispVal4Read()"
            >
              <template
                slot="append"
                v-if="field.info.moreConfig && field.info.moreConfig.appendText"
                >{{ field.info.moreConfig.appendText }}</template
              >
              <template
                slot="prepend"
                v-if="
                  field.info.moreConfig && field.info.moreConfig.prependText
                "
                >{{ field.info.moreConfig.prependText }}</template
              >
            </el-input>
          </template>
        </template>
      </el-col>
      <!-- <el-col :span="2">
          <i class="el-icon-warning"></i>
        </el-col> -->
      <el-col
        style="text-align: center"
        v-show="field.getUniqueCheck()"
        :span="2"
      >
        <el-tooltip
          :content="
            field.getUniqueCheckMsg().msg ? field.getUniqueCheckMsg().msg : ''
          "
          placement="top"
        >
          <!-- UniqueCheckNone 未校验  UniqueCheckError 错误 UniqueCheckOk 通过 loading 校验中 -->
          <i
            v-if="field.getUniqueCheckMsg().state === 'UniqueCheckNone'"
            style="color: orange"
            class="el-icon-question"
          ></i>
          <i
            v-if="field.getUniqueCheckMsg().state === 'loading'"
            style="color: orange"
            class="el-icon-loading"
          ></i>
          <i
            v-if="field.getUniqueCheckMsg().state === 'UniqueCheckError'"
            style="color: red"
            class="el-icon-error"
          ></i>
          <i
            v-if="field.getUniqueCheckMsg().state === 'UniqueCheckOk'"
            style="color: green"
            class="el-icon-success"
          ></i>
        </el-tooltip>
      </el-col>
      <!-- //v-show="field.hasHistoryData()" -->
      <el-col v-show="field.hasHistoryData()" :span="2">
        <!--显示历史数据按钮-->
        <div>
          <el-button
            @click="$emit('field-history-popup', field)"
            icon="el-icon-notebook-2"
          ></el-button>
        </div>
      </el-col>
    </el-row>
    <el-row slot="error" scope="error">
      <el-col style="display: flex">
        <!-- 显示字段校验错误信息 -->
        <div
          class="el-form-item__error"
          v-show="field.hasValidateError() || field.hasValidatePrompt()"
          :title="field.getAnyValidatePrompt()"
        >
          <!-- v-show="field.hasValidateError() || field.hasValidatePrompt()" -->
          <el-popover
            placement="bottom"
            width="200"
            v-show="field.hasValidateError() || field.hasValidatePrompt()"
            trigger="hover"
            :content="
              field.getAnyValidateError()
                ? field.getAnyValidatePrompt()
                  ? field.getAnyValidateError() + field.getAnyValidatePrompt()
                  : field.getAnyValidateError()
                : field.getAnyValidatePrompt()
                ? field.getAnyValidatePrompt()
                : ''
            "
          >
            <i slot="reference" class="el-icon-warning"></i>
          </el-popover>
          <span class="no-nowrap" v-show="field.hasValidateError()">
            <!-- v-show="field.hasValidateError()" -->
            {{ field.getAnyValidateError() }}
            {{
              field.getAnyValidateError() && field.getAnyValidatePrompt()
                ? ";"
                : ""
            }}
          </span>
          <!-- 显示字段校验提示信息 -->
          <span
            class="el-form-item__prompt no-nowrap"
            v-show="field.hasValidatePrompt()"
          >
            <!-- v-show=" field.hasValidatePrompt()" -->
            {{ field.getAnyValidatePrompt() }}
          </span>
        </div>
        <div
          v-if="
            !getDisabled &&
            field.info.moreConfig !== null &&
            getShowHelpTips(field.info)
          "
          :title="
            field.info.moreConfig && field.info.moreConfig.help_tips
              ? field.info.moreConfig.help_tips
              : ''
          "
          class="help-tips"
        >
          <!-- v-if="(!getDisabled && field.info.moreConfig !== null) && getShowHelpTips(field.info)" -->
          <el-popover
            placement="bottom"
            width="200"
            trigger="hover"
            :content="
              field.info.moreConfig && field.info.moreConfig.help_tips
                ? field.info.moreConfig.help_tips
                : ''
            "
          >
            <i
              slot="reference"
              class="el-icon-question"
              style="color: #03a2ff; font-size: 12px"
            ></i>
          </el-popover>
          <span
            v-show="field.info.moreConfig && field.info.moreConfig.help_tips"
            style="color: #03a2ff; font-size: 12px"
          >
            {{
              field.info.moreConfig && field.info.moreConfig.help_tips
                ? field.info.moreConfig.help_tips
                : ""
            }}</span
          >
          <!-- --- -->
        </div>
      </el-col>
    </el-row>
    <!-- <el-switch
      v-if="field.info.editor === 'json-editor'"
      style="display: block"
      v-model="jsonEditorMode"
      active-color="#13ce66"
      inactive-color="#3883FA"
      active-text="tree"
      inactive-text="text"
    >
    </el-switch> -->
    <!-- <div
      v-if="field.info.editor === 'json-editor'"
      class="flex flex-end"
    >
      <el-radio-group
        v-model="jsonEditorMode"
        size="mini"
        v-if="isArrayJson"
      >
        <el-radio-button label="text">text</el-radio-button>
        <el-radio-button label="tree">tree</el-radio-button>
        <el-radio-button label="table">table</el-radio-button>
      </el-radio-group>
      <el-switch
        v-else
        style="display: block"
        active-color="#13ce66"
        inactive-color="#3883FA"
        active-text="树模式"
        inactive-text="代码模式"
        active-value="tree"
        inactive-value="text"
        v-model="jsonEditorMode"
      >
      </el-switch>
    </div> -->
  </div>
</template>

<script>
import InputRange from "../ui/input-range.vue";
import Finder from "../ui/finder.vue";
import multiFinder from "../ui/multi-finder.vue";
import UEditor from "../ui/ueditor.vue";
import TinymceEditor from "./tinymce/index.vue";
// import UploadFile from "../ui/upload-file.vue";
import UploadImage from "../ui/upload-image.vue";
import TreeFinder from "../ui/tree-finder.vue";
import BxInputNumber from "../ui/bx-input-number.vue";
import Userlist from "../ui/userlist.vue";
import QrCode from "../ui/qrcode.vue";
import CodeEditor from "../ui/code-editor.vue";
// import JsonEditor from 'json-editor-vue'
import vueJsonEditor from "vue-json-editor-fix-cn";
import jsonTableEditor from "../ui/json-table-editor/index.vue";

import Radio from "../ui/radio.vue";
import Checkbox from "../ui/checkbox.vue";
import ueditorPlus from "../ui/ueditor-plus.vue";
// import tiptapEditor from "../ui/tiptap-editor/video-home.vue";
import wangEditor from "../ui/wang-editor/wang-editor.vue";
import dynamicSubTemp from "../ui/dynamic-sub-temp.vue"; // 动态子组件
import verifyMobile from "../ui/verifyMobile.vue"; // 手机验证码
import autocompleteInput from "../ui/autocomplete-input.vue"; // 手机验证码
import carNoKeyboard from "../ui/car-no-keyboard.vue"; //车牌号输入
// import transferVue from "../ui/form-widget/transfer.vue";
import transferVue from "../ui/form-widget/multi-select/index.vue"; // 多选穿梭框组件
import { blobToBase64 } from "../../common/common";
import { evalJson } from "@/util/evalJsonExpr.js";
import { Icon } from "@iconify/vue2";
export default {
  components: {
    Checkbox,
    Radio,
    CodeEditor,
    // JsonEditor,
    vueJsonEditor,
    jsonTableEditor,
    Userlist,
    BxInputNumber,
    TreeFinder,
    UploadImage,
    // UploadFile,
    UploadFile: () => import("../ui/upload-file.vue"), //异步组件加载方式,
    InputRange,
    Finder,
    ueditorPlus,
    wangEditor,
    // tiptapEditor,
    ueditor: UEditor,
    TinymceEditor,
    QrCode,
    multiFinder,
    dynamicSubTemp,
    verifyMobile,
    autocompleteInput,
    carNoKeyboard,
    transferVue,
    Icon,
  },

  props: {
    field: Object,
    childForeignkey: {
      type: Object,
    },
    defaultCondition: {
      typeof: Array,
    },
    mainformDatas: {
      type: Object,
    },
    defaultValues: {
      type: Object,
    },
    formModel: {
      type: Object,
    },
  },
  watch: {},

  data() {
    return {
      key: null,
      isTreeJsonEditor: false,
      jsonEditorMode: "text",
      finderSelected: "",
      pickerOptions: {
        disabledDate: (time) => {
          return this.field.info.subType === "year"
            ? this.dealDisabledDate(new Date(time).getFullYear().toString())
            : this.dealDisabledDate(time);
        },
      },
      inputStatus: "",
    };
  },
  computed: {
    getJsonModel() {
      let val = this.field.model;
      try {
        let json = JSON.parse(val);
        return json;
      } catch (error) {
        return null;
      }
    },
    isArrayJson() {
      return (
        this.field.info.editor === "json-editor" &&
        this.field.model &&
        Array.isArray(JSON.parse(this.field.model))
      );
    },
    uploadLimit() {
      const config = this.field.info?.moreConfig;
      return config?.fileLimit || config?.limit || 100;
    },
    updatableJson() {
      if (this.field?.info?.srvCol?.updatable_json) {
        const jsonStr = this.field.info.srvCol.updatable_json;
        return JSON.parse(jsonStr);
      }
    },
    updatable() {
      if (this.updatableJson) {
        return evalJson(this.updatableJson, this.formModel);
      }
    },
    elIconPrefix() {
      return (
        (this.field?.info?.srvCol?.table_name === "bxfile_icon_db" &&
          this.field.info.srvCol.columns === "icon_val" &&
          this.field.model?.includes("el-icon-") &&
          this.field.model) ||
        ""
      );
    },
    cfgJson() {
      let cfgJson = this.field.info.srvCol?.col_cfg_json;
      if (cfgJson) {
        try {
          cfgJson = JSON.parse(cfgJson);
        } catch (error) {}
      }
      return cfgJson;
    },
    customInputVar() {
      if (this.cfgJson?.col_style_df_json) {
        const colStyle = this.cfgJson.col_style_df_json;
        const keys = Reflect.ownKeys(colStyle);
        let str = ``;
        if (keys.length > 0) {
          keys.forEach((key) => {
            str += `;--custom-input-${key}:${colStyle[key]}`;
          });
        }
        return str;
      }
    },
    getDisabled: function () {
      return !this.field.evalEditable() || this.updatable === false;
    },
    queryInitValue() {
      return {
        ...(this.field.info?.queryInitValue || {}),
      };
    },
    dateRangePickerOptions() {
      if (this.queryInitValue?.query_scope_max) {
        return {
          disabledDate: (time) => {
            console.log(time);
            if (this.queryInitValue.type === "日") {
              return time.getTime() > Date.now() - 8.64e7;
            }
          },
        };
      }
    },
  },

  created: function () {
    this.field.editor = this;
  },

  mounted: function () {},

  methods: {
    jsonError(e) {
      if (
        e?.message?.includes(`Parse error on line 1:

^`)
      ) {
        console.log("clear");
        this.field.model = null;
      }
    },
    jsonChange(updatedContent) {
      if (updatedContent) {
        let json = updatedContent;
        let isValid = false;
        try {
          JSON.parse(JSON.stringify(json));
          isValid = true;
        } catch (error) {
          isValid = false;
        }
        if (isValid) {
          this.field.model = JSON.stringify(json);
          this.$emit("field-value-changed", this.field.info.name, this.field);
        }
      }
    },
    getShowHelpTips(e) {
      if (e.moreConfig && e.moreConfig.hasOwnProperty("help_tips")) {
        return true;
      } else {
        return false;
      }
    },
    autocompleteSelected(field) {
      this.$emit("field-value-changed", field.info.name, field);
      // autocomplete字段手动改变下拉选项，通知表单组件进行冗余
      this.field?.form?.handleFieldFkRedundant?.(
        field,
        field?.form?.fields,
        true
      );
    },
    changeDependField(field) {
      if (
        this.field.info?.editor === "date-time-range" &&
        this.queryInitValue?.query_scope_max
      ) {
        if (this.field.model.length === 2) {
          let oneUnitTimes, rangeMaxTimes, unit;
          const startDayTimes = new Date(this.field.model[0]).getTime();
          const endDayTimes = new Date(this.field.model[1]).getTime();
          switch (this.queryInitValue.type) {
            case "日":
              unit = "天";
              oneUnitTimes = 24 * 60 * 60 * 1000;
              break;
            case "月":
              unit = "个月";
              oneUnitTimes = 24 * 60 * 60 * 1000 * 31;
              break;
            case "年":
              unit = "年";
              oneUnitTimes = 24 * 60 * 60 * 1000 * 365;
              break;
          }
          rangeMaxTimes = this.queryInitValue?.query_scope_max * oneUnitTimes;
          if (
            rangeMaxTimes &&
            !isNaN(rangeMaxTimes) &&
            endDayTimes - startDayTimes > rangeMaxTimes
          ) {
            this.field.model = [];
            return this.$message.warning(
              `选择范围不能超过${this.queryInitValue?.query_scope_max}${unit}`
            );
          }
        }
      }
      this.$emit("field-value-changed", field.info.name, field);
    },
    checkLength(val) {
      const validateCnChar = this.field.info?.rules?.find(
        (item) => item.name === "ngMaxlength" && item.encode === "en"
      );
      if (validateCnChar?.ngMaxlength) {
        let b = 0; // 输入的字符数
        for (let i = 0, length = val.length; i < length; i++) {
          let c = val.charAt(i);
          if (/^[\u0000-\u00ff]$/.test(c)) {
            b++;
          } else {
            // 中文占两个字符
            b += 2;
          }
          if (b > Number(validateCnChar?.ngMaxlength)) {
            // 字符长度限制
            this.field.model = val.substr(0, i);
            this.$message.warning(
              `最多输入${validateCnChar?.ngMaxlength}个字符,一个汉字占两个字符`
            );
            if (/^[\u0000-\u00ff]$/.test(c)) {
              b--;
            } else {
              b -= 2;
            }
            break;
          }
        }
      }
    },
    selectChange() {
      if (!this.field.model) {
        this.field.model = null;
      }
      this.$emit("field-value-changed", this.field.info.name, this.field);
    },
    onBlur() {
      this.inputStatus = "";
      // 校验唯一性
      let self = this;
      let isUniqueCheck = this.field.info.isUniqueCheck;
      let config = this.field.info.moreConfig;
      let model = this.field.form.srvValFormModel();

      if (
        config &&
        config.hasOwnProperty("uniqueCheck") &&
        isUniqueCheck.state !== "none" &&
        this.field.model !== null &&
        this.field.model !== ""
      ) {
        let cfg = config.uniqueCheck;
        isUniqueCheck.state = "loading";
        self.isUniqueCheck(cfg, model).then((res) => {
          if (res.data.state == "SUCCESS" && res.data.data.length === 0) {
            isUniqueCheck.state = "UniqueCheckOk";
            isUniqueCheck.msg = "可用";
          } else {
            self.field.model = "";
            isUniqueCheck.state = "UniqueCheckError";
            isUniqueCheck.msg = cfg && cfg.errorText ? cfg.errorText : "";
          }
        });
      } else if (
        config &&
        this.field.model !== null &&
        this.field.model !== ""
      ) {
        let cfg = config.uniqueCheck;
        isUniqueCheck.state = "UniqueCheckError";
        isUniqueCheck.msg = cfg && cfg.errorText ? cfg.errorText : "";
      }
      // 校验唯一性结束
      // this.$emit('blur', this.field)
      // this.field.form && this.field.form.handleValidation && this.field.form.handleValidation(this.field.info.name)
    },

    /**
     * 是否使用控件而非简单html snippet
     * @returns {boolean}
     */
    ifUseRawFieldEditor() {
      let readonlySupportEditors = new Set([
        "upload-file",
        "upload-image",
        "ueditor",
        "snote",
        "qrcode",
        "finder",
        "tree-finder",
        "multifinder",
      ]);
      let linkSupportEditors = new Set(["finder", "tree-finder"]); //
      let editorSupportReadonly = readonlySupportEditors.has(
        this.field.info.editor
      );
      let editorSupportLink = linkSupportEditors.has(this.field.info.editor);

      if (this.field.info.readonly) {
        return editorSupportReadonly;
      } else {
        if (this.field.info.editable) {
          return true;
        } else {
          // editable = false
          let hasNoLinkUrlFunc = !this.field.info.linkUrlFunc;
          let readonlyUnsupportEditors = new Set(["input-number"]);
          let editorSupportReadonly = !readonlyUnsupportEditors.has(
            this.field.info.editor
          );
          return (
            (hasNoLinkUrlFunc || editorSupportLink) && editorSupportReadonly
          );
        }
      }
    },

    getLinkUrl() {
      let data =
        this.field && this.field.form && this.field.form.srvValFormModel();
      if (this.field.info.linkUrlFunc) {
        let url = this.field.info.linkUrlFunc(data, this);
        // 处理url menuapp , 如果用户url 携带 menuapp 不为空 则更新 sessionStorage current_app
        if (url.indexOf("menuapp=") === -1) {
          if (url.indexOf("?") === -1) {
            url = url + "?menuapp=" + sessionStorage.getItem("current_app");
          } else {
            url = url + "&menuapp=" + sessionStorage.getItem("current_app");
          }
        } else {
          let menuapp = "";
          // a.substr(a.indexOf("menuapp=") + 8,a.lastIndexOf("&") - a.indexOf("menuapp=") - 8)
          if (
            url.lastIndexOf("&") !== -1 &&
            url.lastIndexOf("&") > url.indexOf("menuapp=")
          ) {
            menuapp = url.substr(
              url.indexOf("menuapp=") + 8,
              url.lastIndexOf("&") - url.indexOf("menuapp=") - 8
            );
          } else {
            menuapp = url.substr(url.indexOf("menuapp=") + 8, url.length);
          }
          if (menuapp.length > 0) {
            sessionStorage.setItem("current_app", menuapp);
          }
        }
        return url;
      }
    },

    onLinkClicked() {
      let tabTitle =
        (this.field.info.srvCol &&
          this.field.info.srvCol.option_list_v2 &&
          this.field.info.srvCol.option_list_v2.service_label) ||
        "详情";
      // this.addTabByUrl(this.getLinkUrl(), tabTitle)

      let linkUrl = this.getLinkUrl();
      // linkUrl = linkUrl + '&openlayer=true'
      if (
        typeof linkUrl === "string" &&
        (linkUrl.indexOf("?openlayer=") !== -1 ||
          linkUrl.indexOf("&openlayer=") !== -1)
      ) {
        let paramStr =
          linkUrl.indexOf("?") !== -1
            ? linkUrl.slice(linkUrl.indexOf("?") + 1)
            : "";
        let paramArr = [];
        if (paramStr) {
          paramArr = paramStr.split("&");
        }
        let result = false;
        paramArr.forEach((item) => {
          if (item.indexOf("openlayer=") !== -1) {
            result = item.split("openlayer=")[1];
          }
        });
        if (result == "true") {
          top.layer.open({
            type: 2,
            area: ["70%", "60%"],
            content: this.getLinkUrl(), //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
          });
        } else {
          this.addTabByUrl(this.getLinkUrl(), tabTitle);
        }
        // linkUrl = linkUrl.slice(start,)
      } else {
        this.addTabByUrl(this.getLinkUrl(), tabTitle);
      }
    },
    getMoreInfo(e) {
      this.field.moreInfo = e || null;
      console.log("self", e);
    },
    setSrvVal(srvVal) {
      if (this.isSpecial()) {
        this.$refs.editor.setSrvVal(srvVal);
      }
    },

    getSrvVal() {
      if (this.isSpecial()) {
        return this.$refs.editor.getSrvVal();
      }
    },

    isSpecial() {
      return this.$refs.editor && !!this.$refs.editor.setSrvVal;
    },
    dealDisabledDate(time) {
      // 一天的毫秒数 = 8.64e7  判断时在return处可进行加减
      let fi = this.field.info;
      let min = null;
      let max = null;
      let rangMax = "2050-12-30";
      let rangMin = "1980-12-30";

      if (
        new Date(rangMax).getFullYear() >= new Date(time).getFullYear() &&
        new Date(time).getFullYear() >= new Date(rangMin).getFullYear()
      ) {
        if (this.field.info.editor === "DateRange") {
          if (
            fi._DateMaxMin.hasOwnProperty("min") &&
            fi._DateMaxMin.hasOwnProperty("max")
          ) {
            min =
              fi._DateMaxMin.min === "" ||
              fi._DateMaxMin.min === null ||
              fi._DateMaxMin.min === undefined
                ? "1980-01-01"
                : new Date(fi._DateMaxMin.min).getTime();
            max =
              fi._DateMaxMin.max === "" ||
              fi._DateMaxMin.max === null ||
              fi._DateMaxMin.max === undefined
                ? "2050-12-30"
                : new Date(fi._DateMaxMin.max).getTime();
            return !(time.getTime() < max && time.getTime() > min);
          } else {
            return true;
          }
        } else if (this.field.info.editor === "date-picker") {
          if (this.field.info.subType === "year") {
            if (fi.moreConfig.hasOwnProperty("maxMin")) {
              min =
                fi.moreConfig.maxMin.minDate === "" ||
                fi.moreConfig.maxMin.minDate === null ||
                fi.moreConfig.maxMin.minDate === undefined
                  ? "1970"
                  : fi.moreConfig.maxMin.minDate;
              max =
                fi.moreConfig.maxMin.maxDate === "" ||
                fi.moreConfig.maxMin.maxDate === null ||
                fi.moreConfig.maxMin.maxDate === undefined
                  ? "2099"
                  : fi.moreConfig.maxMin.maxDate;
              if (min.indexOf("{") !== -1 && min.indexOf("}") !== -1) {
                // min = min.match(/{(\S*)}/)[1]
                min = min.substring(min.indexOf("{") + 1, min.indexOf("}"));
                min = eval(min);
              }
              if (max.indexOf("{") !== -1 && max.indexOf("}") !== -1) {
                // max = max.match(/{(\S*)}/)[1]
                max = max.substring(max.indexOf("{") + 1, max.indexOf("}"));
                max = eval(max);
              }

              return !(
                new Date(time).getFullYear() <= max &&
                new Date(time).getFullYear() >= min
              );
            } else {
              return true;
            }
          }
        }
      } else {
        return false;
      }
    },
    setImgUrl(url) {
      if (url) {
        if (url.indexOf("http") > -1) {
          return url;
        } else {
          return `${window.backendIpAddr}${url}`;
        }
      } else {
        return "";
      }
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
:deep(.jse-main) {
  max-height: 300px;
}

:deep(.jsoneditor-vue) {
  height: 200px;
  .jsoneditor {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    .jsoneditor-menu {
      background-color: #ebebeb;
      border-bottom-color: #ebebeb;
      color: #3883fa;
      button.jsoneditor-format {
        background-position: -168px -0px;
      }
      button.jsoneditor-compact {
        background-position: -192px -0px;
      }
      .jsoneditor-poweredBy {
        display: none;
      }
      .jsoneditor-modes {
        .jsoneditor-separator {
          color: #333;
        }
      }
    }
  }
}
.color-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 15px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  &.focus {
    border-color: var(--primary-color, #3883fa);
  }
  .color-picker-input {
    width: 30px;
    height: 30px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    margin-right: 5px;
    padding: 0 !important;
  }
  .color-picker-text {
    outline: none;
    border: none;
    flex: 1;
    max-width: 80%;
  }
}
.help-tips {
  color: #c0c4cc;
  /* position:absolute; */
  top: 18px;
  line-height: 1rem;
  white-space: nowrap;
  /*保证文本内容不会自动换行，如果多余的内容会在水平方向撑破单元格*/
  overflow: hidden;
  /*隐藏超出单元格的部分*/
  text-overflow: ellipsis;
  /*将被隐藏的那部分用省略号代替*/
}

.el-input__suffix {
  line-height: initial;
}

.el-select {
  width: 100%;
}

.el-date-editor {
  width: 100% !important;
  max-width: initial !important;
}

.el-input-number {
  width: 100%;
  max-width: initial !important;
}

.el-cascader {
  width: 100%;
}

.raw_field_editor {
  position: relative;

  ::v-deep input {
    /* 配置的字段样式 */
    color: var(--custom-input-color) !important;
    /* font: var(--custom-input-font)!important; */
    /* overflow: var(--custom-input-overflow)!important; */
    font-size: var(--custom-input-font_size) !important;
    /* white-space: var(--custom-input-white_space)!important; */
    text-align: var(--custom-input-text_align) !important;
    /* text-overflow:var(--custom-input-text_overflow)!important; */
    /* border-radius:var(--custom-input-border_radius)!important; */
    /* border:var(--custom-input-border,1px solid #DCDFE6)!important; */
    padding: var(--custom-input-padding, 0 15px) !important;
    /* height:var(--custom-input-height,40px)!important; */
    margin: var(--custom-input-margin) !important;
    font-weight: var(--custom-input-font_weight) !important;
    /* line-height:var(--custom-input-line_height,40px)!important; */
  }

  ::v-deep .el-input--prefix .el-input__inner {
    padding-left: 30px !important;
  }
}

.el-button {
  padding-left: 8px;
  padding-right: 8px;
  border-width: 0px;
}

.el-form-item__error {
  padding-top: 2px;
  /* display: flex; */
  /* width: 100%; */
  /* position: relative; */
  position: relative !important;
  margin-bottom: 5px;
}

.no-nowrap {
  white-space: nowrap;
  /*保证文本内容不会自动换行，如果多余的内容会在水平方向撑破单元格*/
  overflow: hidden;
  /*隐藏超出单元格的部分*/
  text-overflow: ellipsis;
  /*将被隐藏的那部分用省略号代替*/
}

.el-form-item__prompt {
  width: 10rem;
  overflow: hidden;
  /*隐藏超出单元格的部分*/
  color: orange;
  font-size: 12px;
}

.el-input.is-disabled .el-input__inner {
  color: #303133 !important;
}

::v-deep .el-upload__tip {
  line-height: normal;
  margin: 5px 0;
}
</style>
